package com.edgar.redis;

import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.logging.Logger;

/**
 * @author liqs
 * @version 1.0
 * @date 2021/6/10 8:50
 */
public class RedisCache {

    private Logger logger = Logger.getLogger(RedisCache.class.toString());
    private Jedis jedis;
    private String dataSourceName;

    public RedisCache(String host, int port) {
        jedis = new Jedis(host, port);
        if (!jedis.ping().equals("PONG")) {
            logger.info("can not connect redis, host:" + host + "port:" + port);
        }
    }

    public String getDataSourceName() {
        return dataSourceName;
    }

    public void setDataSourceName(String dataSourceName) {
        this.dataSourceName = dataSourceName;
    }

    /**
     * 数据源名称为 supermap 存储为一个列表  一个数据源可对应多个数据集
     * @param datasetname
     */
    public void setDataSetName(String datasetname) {
        jedis.lpush(dataSourceName, datasetname);
    }

    /**
     * 为数据集插入记录集，数据集结构为 hash 列表，
     * key 即为 数据集名称  value 为 Map<String1, String1>  ----> String1 表示记录集 ID  String2 表示记录集对应的属性值
     * @param dataSetName
     * @param recordsetKey
     * @param recordsetValue
     */
    public void setRecordSet(String dataSetName, String recordsetKey, String recordsetValue) {
        jedis.hset(dataSetName, recordsetKey, recordsetValue);
    }

    /**
     * 根据数据集名称返回记录集的迭代器
     * 数据集实质为 hash 结构存储，迭代器是为了方便返回数据
     * @param dataSetName
     * @return
     */
    public RedisDataSetIerator getRecordSet(String dataSetName) {
        return new RedisDataSetIerator(jedis, dataSetName);
    }

    /**
     * 在 DataSource 列表里面移除已经缓存完的数据集 ID
     * @param dataSetName
     */
    public void removeDataset(String dataSetName) {
        if (jedis.hlen(dataSetName) == 0) {
            jedis.lrem(dataSourceName, 0, dataSetName);
        } else {
            logger.warning("can not delete dataset:" + dataSetName+ ", because there are also datasets that are not cached");
        }
    }

    /**
     * 数据集都已经缓存完毕，直接移除数据集（一般不直接使用）
     */
    public void removeDataSource() {
        List<String> datasetNames = getDatasetNames();
        if (datasetNames.size() == 0) {
            jedis.del(dataSourceName);
        } else {
            logger.warning("can not delete dataSource:" + dataSourceName + ", because there are also datasets that are not cached");
        }
    }

    /**
     * 获取所有缓存数据集名称
     * @return
     */
    public List<String> getDatasetNames(){
        return jedis.lrange(dataSourceName, 0 ,jedis.llen(dataSourceName) - 1);
    }

    /**
     * 获取缓存的数据集个数
     * @return
     */
    public long getCacheDataSetCount() {
        return jedis.llen(dataSourceName);
    }

    /**
     * 当该数据成功存入区块链之后，将 根据记录集 ID 将数据删除
     * @param recordsetID
     */
    public void removeRecordSet(String dataSetName, String recordsetID) {
        jedis.hdel(dataSetName, recordsetID);
    }

    public void clearRedisDB(){
        jedis.flushDB();
    }
}
